﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using System.Web.Management;
using Common.Logging;
using Newtonsoft.Json;
using Qy.Yzrb.Helpers;
using Senparc.Weixin;
using Senparc.Weixin.QY.AdvancedAPIs;
using Senparc.Weixin.QY.AdvancedAPIs.MailList;
using Senparc.Weixin.QY.AdvancedAPIs.OAuth2;
using Senparc.Weixin.QY.Containers;
using Senparc.Weixin.QY.Entities;

namespace Qy.Yzrb.Controllers
{
    public class AuthController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(AuthController));
        private static readonly string WxOauth2State = "GbkYin666";

        [AllowAnonymous]
        [HttpGet]
        [ActionName("WxOauth2")]
        public HttpResponseMessage WxOauth2(string url, string code, string state)
        {
            string failedUrl = ConfigurationManager.AppSettings["h5BaseAddress"] + "/401";

            var corpId = ConfigurationManager.AppSettings["qyCorpId"];
            var corpSecret = ConfigurationManager.AppSettings["qyCorpSecret"];

            if (string.IsNullOrEmpty(code))
            {
                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }

            if (state != WxOauth2State)
            {
                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }

            string result = null;
            try
            {
                //tokenResult = Senparc.Weixin.QY.CommonAPIs.CommonApi.GetToken(corpId, corpSecret);
                result = AccessTokenContainer.TryGetToken(corpId, corpSecret);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("获取企业号 AccessToken 出错，授权码:{0},信息：{1}", code, JsonConvert.SerializeObject(ex));

                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }


            GetUserInfoResult userResult;

            try
            {
                userResult = Senparc.Weixin.QY.AdvancedAPIs.OAuth2Api.GetUserId(result, code);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("获取 成员信息出错，授权码:{0},信息：{1}", code, JsonConvert.SerializeObject(ex));

                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }
            if (userResult.errcode != ReturnCode_QY.请求成功)
            {
                Logger.ErrorFormat("获取 成员信息 返回失败，返回结果:{0}", userResult.errcode);

                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }

            var userId = userResult.UserId;
            
            if (string.IsNullOrEmpty(userId))
            {
                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }

            var response = Request.CreateResponse(HttpStatusCode.Redirect);
            response.Headers.Location = new Uri(url);

            //获取企业号用户信息
            GetMemberResult memberInfo = MailListApi.GetMember(result, userResult.UserId);
            //院长办公室:3
            var departCookie = new CookieHeaderValue("AzuDepartCookie",
                JwtTokenHelper.CreateJwtToken(JsonConvert.SerializeObject( memberInfo.department)));
            //cookie.Domain = Request.RequestUri.Host;
            departCookie.Path = "/qy.yzrb/";
            response.Headers.AddCookies(new[] { departCookie });



            var cookie = new CookieHeaderValue("AzuCookie",
                JwtTokenHelper.CreateJwtToken(userId));
            //cookie.Domain = Request.RequestUri.Host;
            cookie.Path = "/qy.yzrb/";
            response.Headers.AddCookies(new[] { cookie });

            //MassApi.SendText(result, userId, "","","4","测试");
//            if (userId == "15018781571")
//            {
//                MassApi.SendFile(result, userId, "", "", "8",
//                    "29RtvpzFOUL9F_xutGLUuP_h9Lhcm7rrUwR-Rgo3gOcFqK1m2ty0hTDiwsB1jgghD");
//            }

            return response;
        }

        [HttpGet]
        [AllowAnonymous]
        [ActionName("Entry")]
        public HttpResponseMessage Entry()
        {
            var h5BaseAddress = ConfigurationManager.AppSettings["h5BaseAddress"];
            var baseAddress = ConfigurationManager.AppSettings["apiBaseAddress"];
            var corpId = ConfigurationManager.AppSettings["qyCorpId"];
            var corpSecret = ConfigurationManager.AppSettings["qyCorpSecret"];

            var url = h5BaseAddress;

            var oauth2Url = Senparc.Weixin.QY.AdvancedAPIs.OAuth2Api.GetCode(corpId, baseAddress
                + "/Auth/WxOauth2?url="
                + HttpUtility.UrlEncode(url), WxOauth2State);

            var response = Request.CreateResponse(HttpStatusCode.Redirect);
            response.Headers.Location = new Uri(oauth2Url);

            return response;
        }
    }
}
